<template>
    <div class="container">
        <div class="pay-box">
            <div class="row1">
                <div>收银：{{ ls.get('USER_INFO').userName }}</div>
                <div class="print-pre" @click="printPre()">打印预结</div>
            </div>
            <div class="pay-content-box">
                <div class="left-box">
                    <el-radio-group v-model="form.actionType" @change="changeActionType">
                        <div class="group-box">
                            <div>
                                <el-radio-button value="折扣优惠" :disabled="!discountCon">折扣优惠</el-radio-button>
                            </div>
                            <div>
                                <el-radio-button value="抹零" :disabled="!rounddownCon">抹零</el-radio-button>
                            </div>
                            <div>
                                <el-radio-button value="服务费" :disabled="!servicechargeCon">服务费</el-radio-button>
                            </div>
                            <div>
                                <el-radio-button value="补低消" :disabled="!supplyminconsumeCon">补低消</el-radio-button>
                            </div>
                            <div class="line"></div>
                            <!-- v-has-role-show="'cashier-payQuery-refund1'" -->
                            <div v-has-role="'order-checkout-wechat'">
                                <img class="img-pay" src="https://oss.jtmckj.com/pc/images/pay/pay-wx.png" alt="">
                                <el-radio-button class="pay-wx" value="微信支付">微信支付</el-radio-button>
                            </div>
                            <div v-has-role="'order-checkout-alipay'">
                                <img class="img-pay" src="https://oss.jtmckj.com/pc/images/pay/pay-ali.png" alt="">
                                <el-radio-button class="pay-ali" value="支付宝支付">支付宝支付</el-radio-button>
                            </div>
                            <div v-has-role="'order-checkout-cash'">
                                <img class="img-pay" src="https://oss.jtmckj.com/pc/images/pay/pay-cash.png" alt="">
                                <el-radio-button class="pay-cash" value="现金">现金</el-radio-button>
                            </div>
                            <div v-has-role="'order-checkout-pos'">
                                <img class="img-pay" src="https://oss.jtmckj.com/pc/images/pay/pay-pos.png" alt="">
                                <el-radio-button class="pay-pos" value="银联POS">银联POS</el-radio-button>
                            </div>
                            <div v-has-role="'order-checkout-membercard'">
                                <img class="img-pay" src="https://oss.jtmckj.com/pc/images/pay/pay-vip.png" alt="">
                                <el-radio-button class="pay-vip" value="会员卡支付">会员卡支付</el-radio-button>
                            </div>
                            <div v-has-role="'order-checkout-other'">
                                <img class="img-pay" src="https://oss.jtmckj.com/pc/images/pay/pay-others.png" alt="">
                                <el-radio-button class="pay-others" value="其他支付">其他支付</el-radio-button>
                            </div>
                            <div class="line"></div>
                            <div v-has-role="'order-checkout-chargeAccount'">
                                <el-radio-button value="挂账">挂账</el-radio-button>
                            </div>
                            <div v-has-role="'order-checkout-gift'">
                                <el-radio-button value="赠送">赠送</el-radio-button>
                            </div>
                            <div class="line"></div>
                            <div v-has-role="'order-checkout-groupTicket'">
                                <el-radio-button value="团购券">团购券</el-radio-button>
                            </div>
                            <div v-has-role="'order-checkout-aggregation'">
                                <el-radio-button value="聚合支付">聚合支付</el-radio-button>
                            </div>
                        </div>
                    </el-radio-group>
                </div>
                <div class="right-box">
                    <div class="pay-title-box">
                        <div class="pay-title">{{ form.actionType }}</div>
                        <div class="pay-unpay" v-if="vipInfo.priceType == '1'">应付金额：￥{{ price }}</div>
                        <div class="pay-unpay" v-else-if="vipInfo.priceType == '2'">应付金额：￥{{ vipPrice }}</div>
                    </div>
                    <Sale v-if="form.actionType == '折扣优惠' && discountCon" ref="SaleRef" :tableInfo="tableInfo"
                        :selectWares="selectWares" :saleData="saleData" :payData="payData" :receive="receive"
                        :form="form" :bookAmtForm='bookAmtForm' :price="price" :yhje="yhje" :unpay="unpay"
                        @focusForm="handleFocusForm" />
                    <Tip v-if="form.actionType == '服务费' && servicechargeCon" ref="TipRef" :tableInfo="tableInfo"
                        :selectWares="selectWares" :saleData="saleData" :payData="payData" :receive="receive"
                        :form="form" :bookAmtForm='bookAmtForm' :price="price" :yhje="yhje"
                        @focusForm="handleFocusForm" />
                    <Cut v-if="form.actionType == '抹零' && rounddownCon" ref="CutRef" :tableInfo="tableInfo"
                        :selectWares="selectWares" :saleData="saleData" :payData="payData" :receive="receive"
                        :form="form" :bookAmtForm='bookAmtForm' :price="price" :yhje="yhje" :unpay="unpay"
                        @focusForm="handleFocusForm" />
                    <Min v-if="form.actionType == '补低消' && supplyminconsumeCon" ref="MinRef" :tableInfo="tableInfo"
                        :selectWares="selectWares" :saleData="saleData" :payData="payData" :receive="receive"
                        :form="form" :bookAmtForm='bookAmtForm' :price="price" :yhje="yhje" :unpay="unpay"
                        @focusForm="handleFocusForm" />

                    <Wechat v-if="form.actionType == '微信支付'" ref="WechatRef" :tableInfo="tableInfo"
                        :selectWares="selectWares" :received="received" :form="form" :price="price" :unpay="unpay"
                        :payData="payData" :saleData="saleData" :details="details" @focusForm="handleFocusForm"
                        @keyupEnter="keyboardComfirm" />
                    <Ali v-if="form.actionType == '支付宝支付'" ref="AliRef" :tableInfo="tableInfo"
                        :selectWares="selectWares" :received="received" :form="form" :price="price" :unpay="unpay"
                        :payData="payData" :saleData="saleData" :details="details" @focusForm="handleFocusForm"
                        @keyupEnter="keyboardComfirm" />
                    <Cash v-if="form.actionType == '现金'" ref="CashRef" :tableInfo="tableInfo" :selectWares="selectWares"
                        :received="received" :form="form" :price="price" :unpay="unpay" :payData="payData"
                        :saleData="saleData" :details="details" @focusForm="handleFocusForm" />
                    <Pos v-if="form.actionType == '银联POS'" ref="PosRef" :tableInfo="tableInfo"
                        :selectWares="selectWares" :received="received" :form="form" :price="price" :unpay="unpay"
                        :payData="payData" :saleData="saleData" :details="details" @focusForm="handleFocusForm" />

                    <Vip v-show="form.actionType == '会员卡支付'" ref="VipRef" :tableInfo="tableInfo"
                        :selectWares="selectWares" :received="received" :form="form" :price="price" :vipPrice="vipPrice"
                        :unpay="unpay" :payData="payData" :saleData="saleData" :details="details" :vipInfo="vipInfo"
                        :coinsPrice="coinsPrice" @focusForm="handleFocusForm" />
                    <Others v-if="form.actionType == '其他支付'" ref="OthersRef" :tableInfo="tableInfo"
                        :selectWares="selectWares" :received="received" :form="form" :price="price" :unpay="unpay"
                        :payData="payData" :saleData="saleData" :details="details" @focusForm="handleFocusForm" />

                    <Credit v-if="form.actionType == '挂账'" ref="CreditRef" :tableInfo="tableInfo"
                        :selectWares="selectWares" :received="received" :form="form" :price="price" :unpay="unpay"
                        :payData="payData" :saleData="saleData" :details="details" @focusForm="handleFocusForm" />
                    <Send v-if="form.actionType == '赠送'" ref="SendRef" :tableInfo="tableInfo" :selectWares="selectWares"
                        :received="received" :form="form" :price="price" :unpay="unpay" :payData="payData"
                        :saleData="saleData" :details="details" @focusForm="handleFocusForm" />

                    <Group v-if="form.actionType == '团购券'" ref="GroupRef" :tableInfo="tableInfo"
                        :selectWares="selectWares" :received="received" :form="form" :price="price" :unpay="unpay"
                        :payData="payData" :saleData="saleData" :details="details" @focusForm="handleFocusForm" />
                    <Poly v-if="form.actionType == '聚合支付'" ref="PolyRef" :tableInfo="tableInfo"
                        :selectWares="selectWares" :received="received" :form="form" :price="price" :unpay="unpay"
                        :payData="payData" :saleData="saleData" :details="details" @focusForm="handleFocusForm" />

                    <div class="queue-box">
                        <div class="queue-right-btn">
                            <div class="btn-items">
                                <div class="item" @click="handleNum('1')">1</div>
                                <div class="item" @click="handleNum('2')">2</div>
                                <div class="item" @click="handleNum('3')">3</div>
                                <div class="item spe" style="margin-right: 0;" @click="handleDelLastNum()"></div>
                            </div>
                            <div class="btn-items">
                                <div class="item" @click="handleNum('4')">4</div>
                                <div class="item" @click="handleNum('5')">5</div>
                                <div class="item" @click="handleNum('6')">6</div>
                                <div class="item" style="margin-right: 0;" @click="handleDelNum()">删除</div>
                            </div>
                            <div class="btn-items">
                                <div class="item" @click="handleNum('7')">7</div>
                                <div class="item" @click="handleNum('8')">8</div>
                                <div class="item" @click="handleNum('9')">9</div>
                                <div class="item">取消</div>
                            </div>
                            <div class="btn-items">
                                <div class="item" @click="handleNum('0')">0</div>
                                <div class="item" @click="handleNum('.')">.</div>
                                <!-- <div class="item item-comfirm" style="margin-right: 0;" @click="keyboardComfirm" :loading="configStore.payFlag" >确认</div> -->
                                <el-button class="item item-comfirm" style="margin-right: 0;" @click="keyboardComfirm" :loading="timeOutFlag || configStore.payFlag" >确认</el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="textarea">
            <el-input v-model="form.remard" type="textarea" :rows="3" placeholder="请输入买单备注" clearable />
        </div>
        <el-button class="submit" @click="handleSubmit">结账</el-button>
    </div>
    <LoadingSpinner :visible="timeOutFlag || configStore.payFlag" />
</template>

<script setup>
import useConfigStore from '@/store/config'

import { formatDecimal } from "@/utils/chenhao";

import Sale from "./payment_sale.vue";
import Tip from "./payment_tip.vue";
import Cut from "./payment_cut.vue";
import Min from "./payment_min.vue";
import Wechat from "./payment_wechat.vue";
import Ali from "./payment_ali.vue";
import Cash from "./payment_cash.vue";
import Pos from "./payment_pos.vue";
import Vip from "./payment_vip.vue";
import Others from "./payment_others.vue";
import Credit from "./payment_credit.vue";
import Send from "./payment_send.vue";
import Group from "./payment_group.vue";
import Poly from "./payment_poly.vue";
import ls from "@/lib/ls";
import { getLocalIPv4 } from "@/utils/getip.js";
import Api from "@/api";

const configStore = useConfigStore()
// 接收父组件参数 props
const props = defineProps({
    tableInfo: {
        type: Object,
        required: false,
    },
    saleData: {
        type: Array,
        required: false,
    },
    payData: {
        type: Array,
        required: false,
    },
    price: {
        type: String,
        required: false,
    },
    receive: {
        type: String,
        required: false,
    },
    received: {
        type: String,
        required: false,
    },
    unpay: {
        type: String,
        required: false,
    },
    selectWares: {
        type: Array,
        required: false,
    },
    vipPrice: {
        type: String,
        required: false,
    },
    vipInfo: {
        type: Object,
        required: false,
    },
    coinsPrice: {
        type: String,
        required: false,
    },
    minConsume: {
        type: Number,
        default: 0,
        required: false
    },
    hasPay: {
        type: Number,
        default: 0,
        required: false
    },
    bookAmtForm: {
        type: Object,
        required: false,
    },
    marketUser: {
        type: String,
        required: false,
    },
    marketUserName: {
        type: String,
        required: false,
    }
});
const price = toRef(props, "price");
const receive = toRef(props, "receive");
const received = toRef(props, "received");
const unpay = toRef(props, "unpay");
const tableInfo = toRef(props, "tableInfo");
const selectWares = toRef(props, "selectWares");
const saleData = toRef(props, "saleData");
const payData = toRef(props, "payData");
const vipPrice = toRef(props, 'vipPrice')
const vipInfo = toRef(props, 'vipInfo')
const coinsPrice = toRef(props, 'coinsPrice')
const minConsume = toRef(props, 'minConsume')
const hasPay = toRef(props, 'hasPay')
const bookAmtForm = toRef(props, 'bookAmtForm')
const marketUserName = toRef(props, 'marketUserName')
const marketUser = toRef(props, 'marketUser')

const emit = defineEmits(["emitSubmit"]);

// let isLoss = router.currentRoute.value.query.loss

let form = ref({
    consumeCode: tableInfo.value.consumeCode,
    actionType: "折扣优惠",
    saleType: "按金额优惠",
    salaAmt: "",
    salaPercent: "",
    finalAmt: "",
    payAmt: unpay.value,
    authCode: "",
    giveChangeAct: "",
    isGiveAct: "0",
    notGiveChange: "",
    payCode: "",
    mobile: "",
    send_remark: "",
    tgqm: "",
    remark: "",
    serviceAmt: [],
});

const resetForm = (params) => {
    form.value.consumeCode = tableInfo.value.consumeCode;
    form.value.actionType = form.value.actionType;
    form.value.salaAmt = "";
    form.value.payAmt = unpay.value;
    form.value.authCode = "";
    form.value.giveChangeAct = "";
    form.value.isGiveAct = "0";
    form.value.notGiveChange = ""
    form.value.payCode = "";
    form.value.remark = "";
    form.value.tgqm = "";
    form.value.ticketName = ""
    form.value.ticketCode = ""
};
const payed = ref('')
const getPayedAmt = () => {
    Api.Common.PcObjProcess.Do({ functionName: "GetConsumeMinConTotalAmt", contentData: { consumeCode: ls.get('TABLE_INFO').consumeCode } })
        .then((res) => {
            if (res.consumeCode == ls.get('TABLE_INFO').consumeCode) {
                payed.value = res.totalAmt
            }

        })
}

onMounted(async () => {
    getPayedAmt()
});
// 切换操作按钮
const changeActionType = (v) => {
    resetForm();
    if (form.value.actionType == "折扣优惠") {
        form.value.saleType = "按金额优惠";
    } else if (form.value.actionType == "服务费") {
        form.value.saleType = "按固定金额";
    } else if (form.value.actionType == "抹零") {
        form.value.saleType = "正向抹零";
    } else if (form.value.actionType == "其他支付") {
        // form.value.payType_btnType = "招待";
    } else if (form.value.actionType == "团购券") {
        form.value.payType_btnType = "美团券";
    } else if (form.value.actionType == "补低消") {
        if (Number(tableInfo.value.minConsume) > (Number(unpay.value) + Number(payed.value))) {
            form.value.salaAmt = tableInfo.value.minConsume - unpay.value - payed.value
        }
    }

};

// --------------------------------------------计算属性---------------------------------------
// ----------------计算优惠金额------------------
const yhje = computed(() => {
    // console.log('form.value.saleType :>> ', form.value.saleType);
    if (form.value.actionType == "折扣优惠") {
        if (form.value.saleType == "按金额优惠") {
            if (!form.value.salaAmt) return;
            return formatDecimal(form.value.salaAmt);
        } else if (form.value.saleType == "按折扣优惠") {
            if (form.value.salaPercent > 0 && form.value.salaPercent <= 10) {
                return formatDecimal(
                    price.value - price.value * (form.value.salaPercent * 0.1)
                );
            }
        } else if (form.value.saleType == "输入付款金额") {
            if (form.value.finalAmt) {
                return formatDecimal(price.value - form.value.finalAmt);
            }
        }
    } else if (form.value.actionType == "服务费") {
        if (form.value.saleType == "按固定金额") {
            if (!form.value.salaAmt) return;
            return formatDecimal(form.value.salaAmt);
        } else if (form.value.saleType == "按百分比") {
            if (form.value.salaPercent > 0) {
                return formatDecimal(
                    price.value * (form.value.salaPercent * 0.01)
                );
            }
        }
    } else if (form.value.actionType == "抹零") {
        if (form.value.saleType == "正向抹零") {
            if (!form.value.salaAmt) return;
            return formatDecimal(form.value.salaAmt);
        }
    } else if (form.value.actionType == "补低消") {
        if (!form.value.salaAmt) return;
        return formatDecimal(form.value.salaAmt);
    }
});

const isAdd = ref(false);
// 下单接口
// 获取缓存里的菜单用来判断是否是点餐路由跳转来的,如果是就要下单
let details = ref([]);
const order = async (params) => {
    const waresOrder = ls.get("WARES_ORDER") || [];
    if (waresOrder && waresOrder.length > 0) {
        waresOrder.forEach(ware => {
            if (ware.subGoods && ware.subGoods.length > 0) {
                console.log('11111 :>> ', 11111);
                ware.subGoods.forEach(item => {
                    waresOrder.push({
                        ...item,
                        goodsPriceCode: item.packageCode,
                        itemType: "3",
                        doType: "add",
                    })
                });
            }
        })
        isAdd.value = true;
        let router_orderBatchCode = router.currentRoute.value.query.orderBatchCode
        let contentData = {
            consumeCode: ls.get("TABLE_INFO").consumeCode,
            roomCode: ls.get("TABLE_INFO").roomCode,
            // consumeCode: "0004202402050006",
            // roomCode: "0004003",
            operType: "",
            detail: waresOrder,
            orderBatchCode: router_orderBatchCode,
            payType: '2',
            remark: router.currentRoute.value.query.remark
        };
        calculateOrderQty(contentData.detail)
        // console.log("waresOrder :>> ", waresOrder);
        // return
        contentData.marketUserName = marketUserName.value
        contentData.marketUser = marketUser.value
        await Api.Common.PcObjProcess.Do({
            functionName: "orderAdd",
            contentData,
        }).then((res) => {
            console.log("下单 res :>> ", res);
            details.value = res.dataList.map((item) => {
                return item.itemCode;
            });
            ls.remove("WARES_ORDER");
        }).catch((err)=> {
            configStore.payFlag = false 
            throw new Error("报错");
        })
    }
};

// 套餐子项数量调整
function calculateOrderQty(items) {
    // 首先按 indexStr 分组
    const groupedItems = {};
    items.forEach(item => {
        if (!groupedItems[item.indexStr]) {
            groupedItems[item.indexStr] = [];
        }
        groupedItems[item.indexStr].push(item);
    });

    // 处理每个分组
    for (const indexStr in groupedItems) {
        const group = groupedItems[indexStr];
        let itemType2OrderQty = null;

        // 找到itemType为2的对象，并记录其orderQty
        group.forEach(item => {
            if (item.itemType == '2') {
                itemType2OrderQty = item.orderQty;
            }
        });

        if (itemType2OrderQty != null) {
            // 计算其它对象的orderQty乘以itemType为2的对象的orderQty
            group.forEach(item => {
                if (item.itemType == '3') {
                    item.orderQty = Number(itemType2OrderQty) * Number(item.orderQty);
                }
            });
        }
    }

    return items;
}

// 虚拟键盘确定
const SaleRef = ref();
const TipRef = ref();
const CutRef = ref();
const MinRef = ref();
const WechatRef = ref();
const AliRef = ref();
const CashRef = ref();
const PosRef = ref();
const VipRef = ref();
const OthersRef = ref();
const CreditRef = ref();
const SendRef = ref();
const GroupRef = ref();
const PolyRef = ref();


const timeOutFlag = ref(false)
const keyboardComfirm = async (params) => {
    if (unpay.value == 0 && form.value.actionType != "折扣优惠" && form.value.actionType != "服务费" && form.value.actionType != "抹零" && form.value.actionType != "补低消") {
        ElNotification({
            title: "提示",
            message: "代付金额为0，无需付款！",
            type: "warning",
        });

        return
    }
    if(timeOutFlag.value){
        ElNotification({
            title: "提示",
            message: "支付中。请稍等",
            type: "warning",
        });
    }
    timeOutFlag.value = true
    setTimeout(() => {
        timeOutFlag.value = false
    }, 1000);
    if (configStore.payFlag) {
        ElNotification({
            title: "提示",
            message: "支付中。请稍等",
            type: "warning",
        });

        return
    }
    // 左边是 折扣优惠
    if (form.value.actionType == "折扣优惠") {
        if (!yhje.value) return;
        await SaleRef.value.handleKeyboardConfirm();
    } else if (form.value.actionType == "服务费") {
        if (!yhje.value) return;
        await TipRef.value.handleKeyboardConfirm();
    } else if (form.value.actionType == "抹零") {
        if (!yhje.value) return;
        // if (!CutRef.value.handleKeyboardConfirm(yhje.value)) return
        await CutRef.value.handleKeyboardConfirm();
    } else if (form.value.actionType == "补低消") {
        if (!yhje.value) return;
        await MinRef.value.handleKeyboardConfirm();
    } else if (form.value.actionType == "微信支付") {
        configStore.payFlag = true // 支付开关
        await order();
        await WechatRef.value.handleKeyboardConfirm();
    } else if (form.value.actionType == "支付宝支付") {
        configStore.payFlag = true // 支付开关
        await order();
        await AliRef.value.handleKeyboardConfirm();
    } else if (form.value.actionType == "现金") {
        configStore.payFlag = true // 支付开关
        await order();
        await CashRef.value.handleKeyboardConfirm();
    } else if (form.value.actionType == "银联POS") {
        configStore.payFlag = true // 支付开关
        await order();
        await PosRef.value.handleKeyboardConfirm();
    } else if (form.value.actionType == "会员卡支付") {
        configStore.payFlag = true // 支付开关
        await order();
        await VipRef.value.handleKeyboardConfirm();
    } else if (form.value.actionType == "其他支付") {
        configStore.payFlag = true // 支付开关
        await order();
        await OthersRef.value.handleKeyboardConfirm();
    } else if (form.value.actionType == "挂账") {
        configStore.payFlag = true // 支付开关
        await order();
        await CreditRef.value.handleKeyboardConfirm();
    } else if (form.value.actionType == "赠送") {
        configStore.payFlag = true // 支付开关
        await order();
        await SendRef.value.handleKeyboardConfirm();
    } else if (form.value.actionType == "团购券") {
        configStore.payFlag = true // 支付开关
        await order();
        await GroupRef.value.handleKeyboardConfirm();
    } else if (form.value.actionType == "聚合支付") {
        configStore.payFlag = true // 支付开关
        await order();
        await PolyRef.value.handleKeyboardConfirm();
    }
    if (form.value.actionType != "折扣优惠" && form.value.actionType != "服务费" && form.value.actionType != "抹零" && form.value.actionType != "补低消") {
        await payBookAmt()
    }
    configStore.payFlag = false; // 确保在所有操作完成后再设置为 false

    console.log(configStore.payFlag,'configStore.payFlag')

};
watch(configStore.ispaying, (newValue, oldValue) => {
    console.log(newValue);
    configStore.payFlag = false; // 确保在所有操作完成后再设置为 false
})
// 预订押金支付
const payBookAmt = async (params) => {

    // 预订押金
    await Api.Common.PcObjProcess.Do({ "functionName": "GetRoomReserveState", "contentData": { roomCode: ls.get('TABLE_INFO').roomCode } })
        .then(res => {

            if (!res.isUseReserveAmt && res.reserveAmt > 0) { //true 已抵扣 false 未抵扣  false可以用
                bookAmtForm.value.bookAmt = res.reserveAmt
                bookAmtForm.value.toolBookAmt = res.reserveAmt
                bookAmtForm.value.bookPayType = res.posPayType
                bookAmtForm.value.bookCardNo = res.cardNo
                bookAmtForm.value.bookTradeNo = res.tradeNo
                console.log('有押金', res);
            } else {
                bookAmtForm.value.bookAmt = 0
                bookAmtForm.value.toolBookAmt = 0
            }
        })
        .catch(err => {
        })
    if (bookAmtForm.value.bookAmt > 0) {
        configStore.payFlag = true // 支付开关
        // 处理勾选的商品
        let detailList = []
        if (details.value.length > 0) {
            console.log('1 :>> ', 1);
            detailList = details.value
        } else {
            console.log('2 :>> ', 2);
            detailList = selectWares.value.map(item => {
                return item.itemCode
            })
        }
        const obj = {
            zffs: bookAmtForm.value.bookCardNo ? '会员卡支付' : '微信支付',
            skje: bookAmtForm.value.bookAmt,
            consumeCode: tableInfo.value.consumeCode,
            payType: bookAmtForm.value.bookPayType,
            totalAmt: unpay.value,
            payAmt: bookAmtForm.value.bookAmt,
            tradeNo: bookAmtForm.value.bookTradeNo,
            cardNo: bookAmtForm.value.bookCardNo,
            isReservePay: "1",
            detailList,
        }
        const data = {
            payType: bookAmtForm.value.bookPayType,
            tradeNo: bookAmtForm.value.bookTradeNo,
            bookCardNo: bookAmtForm.value.bookCardNo,
            consumeCode: tableInfo.value.consumeCode,
            roomCode: tableInfo.value.roomCode,
            payBatchCode: ls.get('payBatchCode'),
            orderAmt: price.value,
            realPayAmt: bookAmtForm.value.bookAmt,
            detailList: detailList.join(','),
            payList: [obj],
            serviceAmt: saleData.value
        }
        await Api.Common.PcObjProcess.Do({ "functionName": "OrderPay", "contentData": data })
            .then(res => {
                configStore.ispaying.id++
                console.log('买单确认res :>> ', res);
                obj.itemCode = res.itemCode
                obj.payBatchCode = res.payBatchCode
                tableInfo.value.payBatchCode = res.payBatchCode
                payData.value.push(obj)
                form.value.payAmt = ''
                form.value.giveChange = ''
                form.value.notGiveChange = ''
                form.value.isGiveAct = '0'
                bookAmtForm.value.bookAmt = 0
                ls.set('payBatchCode', res.payBatchCode)
            })
            .catch(err => {
                configStore.ispaying.id++
            })
    }

}

// 数字键盘操作
// let keyboard = ref(false)
let input = ref("");
const focusForm = (str) => {
    // keyboard.value = true
    input.value = str;
};
const blurForm = (params) => {
    // keyboard.value = false
};
// 点击数字
const handleNum = (str) => {
    form.value[input.value] ? form.value[input.value] += "" : ""
    if (
        form.value[input.value] &&
        form.value[input.value].indexOf(".") !== -1 &&
        str === "."
    )
        return;
    // console.log('form.value[input.value] :>> ', input.value);
    form.value[input.value] += str
    if (input.value && input.value == 'salaPercent') {
        // form.value[input.value] += ""
        if (form.value[input.value] > 9.9) {
            form.value[input.value] = '9.9'
        } else {
            let arr = form.value[input.value].split('.')
            if (arr.length == 2) {
                arr[1] = arr[1][0]
            }
            form.value[input.value] = arr.join('.')
        }
    }
};
const handleDelLastNum = () => {
    form.value[input.value] += ""
    form.value[input.value] = form.value[input.value].slice(
        0,
        form.value[input.value].length - 1
    );
};
const handleDelNum = () => {
    form.value[input.value] = "";
};

// 子组件focus input
const handleFocusForm = (str) => {
    focusForm(str);
};

// 点击桌台
const router = useRouter();

//获取ip地址
const ip = ref("");
getLocalIPv4()
    .then((ipAddress) => {
        // 在这里处理获取到的 IP 地址
        ip.value = ipAddress;
        console.log("IP 地址:", ip.value);
    })
    .catch((error) => {
        console.error("发生错误:", error);
        // 在这里处理错误情况
    });
// 结账押金支付
const checkBookAmt = async () => {
    if (bookAmtForm.value.bookAmt > 0) {
        // 处理勾选的商品
        let detailList = []
        if (details.value.length > 0) {
            console.log('1 :>> ', 1);
            detailList = details.value
        } else {
            console.log('2 :>> ', 2);
            detailList = selectWares.value.map(item => {
                return item.itemCode
            })
        }
        const obj = {
            zffs: bookAmtForm.value.bookCardNo ? '会员卡支付' : '微信支付',
            skje: receive.value,
            consumeCode: tableInfo.value.consumeCode,
            payType: bookAmtForm.value.bookPayType,
            totalAmt: unpay.value,
            payAmt: receive.value,
            tradeNo: bookAmtForm.value.bookTradeNo,
            cardNo: bookAmtForm.value.bookCardNo,
            isReservePay: "1",
            detailList,
        }
        const data = {
            payType: bookAmtForm.value.bookPayType,
            tradeNo: bookAmtForm.value.bookTradeNo,
            bookCardNo: bookAmtForm.value.bookCardNo,
            consumeCode: tableInfo.value.consumeCode,
            roomCode: tableInfo.value.roomCode,
            payBatchCode: ls.get('payBatchCode'),
            orderAmt: price.value,
            realPayAmt: receive.value,
            detailList: detailList.join(','),
            payList: [obj],
            serviceAmt: saleData.value
        }
        await Api.Common.PcObjProcess.Do({ "functionName": "OrderPay", "contentData": data })
            .then(res => {
                console.log('买单确认res :>> ', res);
                obj.itemCode = res.itemCode
                obj.payBatchCode = res.payBatchCode
                tableInfo.value.payBatchCode = res.payBatchCode
                payData.value.push(obj)
                form.value.payAmt = ''
                form.value.giveChange = ''
                form.value.notGiveChange = ''
                form.value.isGiveAct = '0'
                ls.set('payBatchCode', res.payBatchCode)
            })
    }
}

// 点击结账
const CheckoutFlag = ref(false)
const handleSubmit = async () => {
    console.log(unpay.value, '未付金额');
    console.log(received.value, '已收');
    console.log(receive.value, '应收');
    console.log(payData.value);
    if (CheckoutFlag.value) {
        ElNotification({
            title: "提示",
            message: "加载中，请稍等",
            type: "warning",
        });
        return
    }
    CheckoutFlag.value = true
    // return
    // 低消验证
    if (selectWares.value.length <= 0) {
        ElNotification({ title: "提示", message: "请选择未结账商品", type: "warning" });
        CheckoutFlag.value = false
        return
    }
    let selectWaresMinConsume = 0
    selectWares.value.forEach(item => {
        if (item.isJoinMinConsume) {
            selectWaresMinConsume += item.sourceRealAmt
        }
    })
    if ((selectWaresMinConsume + hasPay.value) < minConsume.value) {
        ElNotification({
            title: "提示",
            message: "第一次消费未达到低消，不能进行结账",
            type: "warning",
        });
        CheckoutFlag.value = false
        return
    }
    // 如果押金金额超过应收金额 并且没有支付记录
    if (bookAmtForm.value.bookAmt >= receive.value && payData.value.length == 0) {
        // 押金全额抵扣的情况
        await order();
        await checkBookAmt()


        // 处理勾选的商品
        let detailList = []
        if (details.value.length > 0) {
            detailList = details.value
        } else {
            detailList = selectWares.value.map(item => {
                return item.itemCode
            })
        }
        let data = {
            payBatchCode: tableInfo.value.payBatchCode,
            itemCodeList: detailList.join(','),
            remark: form.value.remard,
            serviceAmt: saleData.value
        };
        Api.Common.PcObjProcess.Do({ functionName: "Checkout", orgCode: "0004", contentData: data, }).then((res) => {
            console.log("调用点击结账接口 res:>> ", res);
            ElNotification({
                title: "提示",
                message: "结账成功",
                type: "success",
            });
            Api.Common.PcObjProcess.Do({
                functionName: "OrderPayPrint",
                orgCode: "0004",
                contentData: { consumeCode: tableInfo.value.consumeCode, "ip": ip.value, "payBatchCode": tableInfo.value.payBatchCode, isAdd: isAdd.value },
            }).then((res) => {
                //console.log('调用点击结账接口 res:>> ', res);
                ElNotification({
                    title: "提示",
                    message: "打印成功",
                    type: "success",
                });
                CheckoutFlag.value = false
                router.push({
                    path: "/order/orderTable",
                });
            });
            emit("emitSubmit", "emitSubmit");
        });
        return
    }
    // 押金不够抵扣的情况

    if (unpay.value != 0) {
        ElNotification({
            title: '提示',
            message: '还有剩余金额未完成支付，请核对后再操作',
            type: 'warning',
        })
        CheckoutFlag.value = false
        return
    }

    if (Number(receive.value) > Number(received.value)) {
        ElNotification({
            title: '提示',
            message: '已收小于应收，无法结账',
            type: 'warning',
        })
        CheckoutFlag.value = false
        return
    }
    if (receive.value != received.value) {
        const cashItems = payData.value.filter(item => item.zffs === '现金');
        // 计算这些元素的 notGiveChange 属性的总和
        const totalNotGiveChange = cashItems.reduce((sum, item) => {
            if (item.notGiveChange) {
                return sum + Number(item.notGiveChange);
            }
            return sum;
        }, 0);
        console.log(totalNotGiveChange);
        if ((totalNotGiveChange + Number(receive.value)) != Number(received.value)) {
            ElNotification({
                title: '提示',
                message: '收款金额与应收金额不符',
                type: 'warning',
            })
            CheckoutFlag.value = false
            return
        }
    }
    // 处理勾选的商品
    let detailList = []
    if (details.value.length > 0) {
        detailList = details.value
    } else {
        detailList = selectWares.value.map(item => {
            return item.itemCode
        })
    }
    let data = {
        payBatchCode: tableInfo.value.payBatchCode,
        itemCodeList: detailList.join(','),
        remark: form.value.remard,
        serviceAmt: saleData.value
    };
    Api.Common.PcObjProcess.Do({ functionName: "Checkout", orgCode: "0004", contentData: data, }).then((res) => {
        console.log("调用点击结账接口 res:>> ", res);
        ElNotification({
            title: "提示",
            message: "结账成功",
            type: "success",
        });
        Api.Common.PcObjProcess.Do({
            functionName: "OrderPayPrint",
            orgCode: "0004",
            contentData: { consumeCode: tableInfo.value.consumeCode, "ip": ip.value, "payBatchCode": tableInfo.value.payBatchCode, isAdd: isAdd.value },
        }).then((res) => {
            //console.log('调用点击结账接口 res:>> ', res);
            ElNotification({
                title: "提示",
                message: "打印成功",
                type: "success",
            });
            CheckoutFlag.value = false
            router.push({
                path: "/order/orderTable",
            });
        });
        emit("emitSubmit", "emitSubmit");
    });
};

const getTicket = () => {
    // console.log('getTicket :>> ', VipRef.value);
    if (VipRef.value) {
        VipRef.value.getTicket()
    }
}
getTicket()
defineExpose({
    details, getTicket
})
const discountCon = ref(false)
const rounddownCon = ref(false)
const servicechargeCon = ref(false)
const supplyminconsumeCon = ref(false)
// 获取支付权限
const getUserMenuButton = () => {
    Api.Common.PcObjProcess.Do({ "functionName": "GetUserMenuButton", "contentData": { obj: "" } }) // order-checkout  order-checkout-else
        .then(res => {
            console.log('res:', res.result);
            discountCon.value = res.result.some(p => p.name == "order-checkout-discount") //折扣优惠
            rounddownCon.value = res.result.some(p => p.name == "order-checkout-rounddown") //抹零权限
            servicechargeCon.value = res.result.some(p => p.name == "order-checkout-servicecharge") //服务费权限
            supplyminconsumeCon.value = res.result.some(p => p.name == "order-checkout-supplyminconsume") //补低消
        })
}
getUserMenuButton();

// 打印预结
const printPre = () => {
    let balanceAmt = "0" //  补低消
    let disCountAmt = "0"   // 折扣
    let serviceAmt = "0"   // 服务费
    let smallChange =  "0"   //抹零
    saleData.value.forEach((item, index) => { 
        if (item.type == "折扣优惠") {
            disCountAmt  = item.amt
        }
        if (item.type == "抹零") {
            smallChange  = item.amt
        }
        if (item.type == "补低消") {
            balanceAmt  = item.amt
        }
        if (item.type == "服务费") {
            serviceAmt  = item.amt
        }
    })
    // 后端强制规定0.00转成0的string
    disCountAmt == '0.00' ? disCountAmt = '0' : disCountAmt
    smallChange == '0.00' ? smallChange = '0' : smallChange
    balanceAmt == '0.00' ? balanceAmt = '0' : balanceAmt
    serviceAmt == '0.00' ? serviceAmt = '0' : serviceAmt 
    let printModal = {
        "functionName": "OrderPrePayPrint",
        "contentData": {
            "consumeCode": tableInfo.value.consumeCode,
            "roomCode": tableInfo.value.roomCode,
            "ip": ip.value,
            "balanceAmt": balanceAmt,
            "disCountAmt": disCountAmt,
            "serviceAmt": serviceAmt,
            "smallChange": smallChange
        }
    } 
    if(tableInfo.value.payBatchCode){
        printModal.contentData.payBatchCode = tableInfo.value.payBatchCode 
    }
    // delete printModal.contentData.payBatchCode
    // console.log('打印预结printModal:',printModal);  return 
    Api.Common.PcObjProcess.Do(printModal).then(res => {
        console.log('打印预结res:',res);
        ElNotification({
            title: "提示",
            message: "打印预结小票成功",
            type: "success",
        });
    })
}

</script>

<style scoped lang="scss">
/* 在这里编写组件的CSS样式 */
.container {
    margin-left: 20px;
    // width: 560px;
    // height: 830px;
    // background: #FFFFFF;
    // border-radius: 8px;

    .pay-box {
        width: 600px;
        height: 658px;
        background: #ffffff;
        border-radius: 8px;
        padding: 19px 21px;

        .row1 {
            font-family: Microsoft YaHei;
            font-weight: 400;
            font-size: 20px;
            color: #212121;
            display: flex;
            flex-direction: row;
            justify-content: space-between;

            .print-pre {
                width: 140px;
                text-align: center;
                line-height: 40px;
                font-size: 20px;
                height: 40px;
                background: #FFD400;
                border-radius: 8px;
            }
        }

        .pay-content-box {
            margin-top: 15px;
            display: flex;
            justify-content: space-between;

            // width: 100%;
            // height: 500px;
            .left-box {
                .group-box {
                    .line {
                        // width: 120px;
                        height: 6px;
                        background: #e6e6e6;
                    }

                    div:first-child {
                        ::v-deep {
                            .el-radio-button__inner {
                                border-radius: 8px 8px 0px 0px;
                            }
                        }
                    }

                    div:last-child {
                        ::v-deep {
                            .el-radio-button__inner {
                                border-radius: 0px 0px 8px 8px;
                                border: 0;
                            }
                        }
                    }
                }

                ::v-deep {
                    // .el-radio-group {
                    //     display: block;
                    // }

                    .el-radio-button {
                        .el-radio-button__inner {
                            width: 120px;
                            height: 40px;
                            line-height: 40px;
                            border-radius: 0px;
                            border: 0;
                            background: #fafafa;
                            border-bottom: 1px solid #e6e6e6;
                            font-weight: 400;
                            font-size: 16px;
                            color: #212121;
                            padding: 0;
                        }
                    }

                    .pay-wx {
                        .el-radio-button__inner {
                            padding-left: 15px;
                        }
                    }

                    .pay-ali {
                        .el-radio-button__inner {
                            padding-left: 30px;
                        }
                    }

                    .pay-cash {
                        .el-radio-button__inner {
                            padding-left: 0px;
                        }
                    }

                    .pay-pos {
                        .el-radio-button__inner {
                            padding-left: 20px;
                        }
                    }

                    .pay-vip {
                        .el-radio-button__inner {
                            padding-left: 30px;
                        }
                    }

                    .pay-others {
                        .el-radio-button__inner {
                            padding-left: 15px;
                        }
                    }

                    .is-active {
                        .el-radio-button__inner {
                            background: #fffbe5;
                            color: #ff6a00;
                        }
                    }
                }

            }

            .right-box {
                width: 100%;
                position: relative;
                margin-left: 20px;
                min-height: 580px;

                .pay-title-box {
                    width: 100%;
                    height: 40px;
                    background: #e6e6e6;
                    border-radius: 8px 8px 0px 0px;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding-left: 20px;
                    padding-right: 16px;

                    .pay-title {
                        font-family: Microsoft YaHei;
                        font-weight: bold;
                        font-size: 18px;
                        color: #212121;
                        line-height: 40px;
                    }

                    .pay-unpay {
                        font-family: Microsoft YaHei;
                        font-weight: 400;
                        font-size: 16px;
                        color: #212121;
                        line-height: 40px;
                    }
                }
            }
        }
    }

    .textarea {
        margin-top: 15px;
        margin-bottom: 25px;
        height: 72px;

        ::v-deep {
            .el-textarea__inner {
                border-radius: 8px;
                border: 0;
                font-size: 16px;
                color: #999999;
                resize: none;
            }
        }
    }

    .submit {
        width: 100%;
        height: 60px;
        background: #ff6a00;
        border-radius: 8px;
        font-weight: 400;
        font-size: 24px;
        color: #ffffff;
    }
}

.queue-box {
    position: absolute;
    bottom: 0px;
    // right: 0px;

    .queue-right-btn {
        margin-top: 20px;

        .btn-items {
            display: flex;
            // align-items: center;
            // justify-content: space-between;
            margin-bottom: 12px;

            .item {
                cursor: pointer;
                width: 95px;
                height: 48px;
                text-align: center;
                background: #e6e6e6;
                border-radius: 8px;
                font-family: Microsoft YaHei;
                font-weight: 400;
                font-size: 20px;
                color: #212121;
                line-height: 48px;
                margin-right: 12px;

                &.spe {
                    background-image: url("https://oss.jtmckj.com/pc/images/queue/i_btn_del.png");
                    background-size: 38px 28px;
                    background-repeat: no-repeat;
                    background-position: center;
                }
            }

            .item-comfirm {
                width: 200px;
                background: #ffd400;
            }
        }

        :last-child {
            margin-bottom: 0px;
        }
    }
}

.img-pay {
    width: 20px;
    height: 20px;
    position: absolute;
    z-index: 1;
    margin-top: 10px;
    margin-left: 8px;
}

:deep(.el-input__wrapper) {
    background: #fff !important;
    border-radius: 8px !important;
    border: 1px solid #E6E6E6 !important;
    box-shadow: none !important;
}

:deep(.el-select__wrapper) {
    background: #fff !important;
    border-radius: 8px !important;
    border: 1px solid #E6E6E6;
    box-shadow: none !important;
}
</style>
